package com.yuhuihui.common.utils;

import com.yuhuihui.common.exception.CommonException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;

/**
 * 字符集工具类
 * 参考 hutool-CharsetUtil
 *
 * @author yuhh
 * @date 2023-05-25 14:04:10
 */
public final class CharsetUtil {

	/** logger */
	private static final Logger logger = LoggerFactory.getLogger(CharsetUtil.class);

	/**
	 * ISO-8859-1
	 */
	public static final Charset CHARSET_ISO_8859_1 = StandardCharsets.ISO_8859_1;

	/**
	 * UTF-8
	 */
	public static final Charset CHARSET_UTF_8 = StandardCharsets.UTF_8;

	/**
	 * GBK
	 */
	public static final String GBK = "GBK";
	/**
	 * GBK
	 */
	public static final Charset CHARSET_GBK = Charset.forName(GBK);

	/**
	 * 转换为Charset对象
	 *
	 * @param charsetName 字符集，为空则返回默认字符集
	 * @return {@link Charset } 字符集
	 * @throws UnsupportedCharsetException 不受支持字符集异常
	 * @author yuhh
	 * @date 2023-05-25 14:04:55
	 */
	public static Charset charset(String charsetName) throws UnsupportedCharsetException {
		if (ObjectUtils.isEmpty(charsetName)) {
			return defaultCharset();
		}

		Charset result;
		try {
			result = Charset.forName(charsetName);
		} catch (UnsupportedCharsetException e) {
			logger.error("{}：无法转换为Charset", defaultCharset(), e);
			result = defaultCharset();
		}
		return result;
	}

	/**
	 * 转换字符串的字符集编码
	 *
	 * @param source      字符串
	 * @param srcCharset  源字符集，默认ISO-8859-1
	 * @param destCharset 目标字符集，默认UTF-8
	 * @return {@link String } 转换后的字符串
	 * @author yuhh
	 * @date 2023-05-25 14:05:10
	 */
	public static String convert(String source, String srcCharset, String destCharset) {
		return convert(source, CharsetUtil.charset(srcCharset), CharsetUtil.charset(destCharset));
	}

	/**
	 * 转换字符串的字符集编码
	 *
	 * @param source      字符串
	 * @param srcCharset  源字符集
	 * @param destCharset 目标字符集
	 * @return {@link String } 转换后的字符集
	 * @author yuhh
	 * @date 2023-05-25 14:05:22
	 */
	public static String convert(String source, Charset srcCharset, Charset destCharset) {
		if (null == srcCharset) {
			throw new CommonException("转换字符串的源字符集为空");
		}

		if (null == destCharset) {
			throw new CommonException("转换字符串的目标字符集为空");
		}

		if (ObjectUtils.isEmpty(source) || srcCharset.equals(destCharset)) {
			return source;
		}
		return new String(source.getBytes(srcCharset), destCharset);
	}

	/**
	 * 获取系统默认字符集编码
	 *
	 * @return {@link Charset } 系统默认字符集编码
	 * @author yuhh
	 * @date 2023-05-25 14:05:37
	 */
	public static Charset defaultCharset() {
		return Charset.defaultCharset();
	}

	/**
	 * 获取系统默认字符集编码名称
	 *
	 * @return {@link String } 系统默认字符集编码名称
	 * @author yuhh
	 * @date 2023-05-25 14:06:11
	 */
	public static String defaultCharsetName() {
		return defaultCharset().name();
	}

	private CharsetUtil(){}
}
